package com.yonyou.pmclouds.basecom.filter;

import com.alibaba.dubbo.rpc.*;
import com.yonyou.pmclouds.basecom.runtime.DevRuntimeEnvironment;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import lombok.extern.slf4j.Slf4j;

/**
 * dubbo 上下文设置过滤器,保证远程调用前，一定设置了上下文
 * <p>注意dubbo使用的，不是http的filter
 */
@Slf4j
public class DubboConsumerContextFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        // 路由规则在filter之前，如果需要使用attachment相关的路由，则考虑调整位置
        RpcContext.getContext().setAttachment(RuntimeEnvironment.KEY_DATA_SOURCE, RuntimeEnvironment.getDataSource());
        if (RuntimeEnvironment.getLanguage() != null) {
            RpcContext.getContext().setAttachment(RuntimeEnvironment.KEY_LANG, RuntimeEnvironment.getLanguage().getValue().getLanguage());
            RpcContext.getContext().setAttachment(RuntimeEnvironment.KEY_COUNTRY, RuntimeEnvironment.getLanguage().getValue().getCountry());
        }
        RpcContext.getContext().setAttachment(RuntimeEnvironment.KEY_LOGIN_USER, RuntimeEnvironment.getLoginUserId());
        RpcContext.getContext().setAttachment(RuntimeEnvironment.KEY_TENANT_ID, RuntimeEnvironment.getTenantId());
        RpcContext.getContext().setAttachment(RuntimeEnvironment.KEY_SYS_ID, RuntimeEnvironment.getSysId());
        RpcContext.getContext().setAttachment(DevRuntimeEnvironment.DEV_DEST_KEY, DevRuntimeEnvironment.getDestHost());

        log.info("Dubbo 远程调用 Context设置完成，method：{}，login_user_id：{}", invocation.getMethodName(), RuntimeEnvironment.getLoginUserId());
        return invoker.invoke(invocation);
    }
}